package com.earthea.scaffold.common.config;

import com.earthea.common.util.CompressionUtils;
import com.earthea.scaffold.common.entity.PageResult;
import com.earthea.scaffold.domain.SysFile;
import com.earthea.scaffold.system.entity.request.SysFileReq;
import com.earthea.scaffold.system.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.SmartLifecycle;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class LifecycleRunner implements SmartLifecycle {
    private volatile boolean running = false;

    @Value("${app.web.resourcePath}")
    private String resourcePath;

    @Autowired
    @Qualifier("singleExecute")
    private ThreadPoolTaskExecutor singleExecute;

    @Autowired
    private SysFileService sysFileService;

    @Override
    public void start() {
        log.info("SmartLifecycle start 方法执行...");

        try {
            running = true;
            CompletableFuture.runAsync(() -> loadSysFile(1, 100), singleExecute);
            log.info("SmartLifecycle 启动完成");
        } catch (Exception e) {
            throw new RuntimeException("启动失败", e);
        }
    }

    private void loadSysFile(int pageNum, int pageSize) {
        SysFileReq req = new SysFileReq();
        req.setPageNum(pageNum);
        req.setPageSize(pageSize);
        PageResult<SysFile> sysFiles = sysFileService.selectPage(req);
        if (sysFiles.isEmpty()) {
            return;
        }
        for (SysFile row : sysFiles.getRows()) {
            File localFile = new File(resourcePath, row.getFileName());
            if (!localFile.exists()) {
                try (FileOutputStream fileOutputStream = new FileOutputStream(localFile)) {
                    fileOutputStream.write(CompressionUtils.decompress(row.getFileData()));
                } catch (IOException e) {
                    log.error("load sysFile [{}] error", row.getFileMd5(), e);
                }
            }
        }
        if (!sysFiles.isLast()) {
            pageNum = pageNum + 1;
            loadSysFile(pageNum, pageSize);
        }
    }

    @Override
    public void stop() {
        log.info("SmartLifecycle stop 方法执行...");
        running = false;
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}
